/**
 * 项目名称（软件名称）：忠旺机械物资管理系统(mms)
 * 研发设计单位：忠旺机械设备制造有限公司机械设计院智能控制设计科设计与研发。
 * 版权所有：忠旺机械设备制造有限公司
 * 注：本项目的一切技术专利，使用规范归解释权由忠旺机械设备制造有限公司所有。
 * 软件版本：Ver 1.0.0
 * 文件路径：com.zhongwang.mms.module.purchase.controller
 * 创建时间：2020年03月16日 12时47分
 **/
package com.zhongwang.mms.module.purchase.controller;

import com.alibaba.fastjson.JSON;
import com.zhongwang.mms.base.BaseController;
import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.gen.entity.PInventory;
import com.zhongwang.mms.gen.entity.Role;
import com.zhongwang.mms.gen.entity.TDept;
import com.zhongwang.mms.module.purchase.constant.PurchaseConstant;
import com.zhongwang.mms.module.purchase.dao.PurPInventoryDao;
import com.zhongwang.mms.module.purchase.model.*;
import com.zhongwang.mms.module.purchase.service.PurWarOutManageService;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.module.system.role.RoleService;
import com.zhongwang.mms.util.ShiroUtils;

import lombok.extern.log4j.Log4j2;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


/**
 * @ClassName： PurWarInManageController
 * @Description： 外购件领料出库控制层
 * @Author： 徐一贺
 * @Date： 2020/3/16 12:47
 * @Version： V1.0
 **/
@Controller
@RequestMapping("/purWarOutManage")
@Log4j2
public class PurWarOutManageController extends BaseController {

    @Autowired
    private PurWarOutManageService purWarOutManageService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PurPInventoryDao purPInventoryDao;
    @Autowired
    private LogService logService;

    /**
     * 领料出库页面
     *
     * @return 页面路径
     */
    @GetMapping("/index/{mode}")
    @RequiresPermissions(value = {"purwar:puroutwar:view", "mecwar:outwar:edit", "ykwar:outwar:edit"}, logical = Logical.OR)
    public String PurWarOutManage(Model model, @PathVariable("mode") String mode) {
        model.addAttribute("mode", mode);
        //获取角色码用来进行控制页面显示内容
        List<Role> roles = new ArrayList<>();
        roles.addAll(roleService.findRolesByUserId(ShiroUtils.getUser().getId()));
        List<String> roleCodes = new ArrayList<>();
        for (Role role : roles) {
            if (role.getRoleCode().equals("W01")) {
                roleCodes.add(role.getRoleCode());
            } else if (role.getRoleCode().equals("W02")) {
            } else if (role.getRoleCode().equals("W02")) {
                roleCodes.add(role.getRoleCode());
            } else if (role.getRoleCode().equals("W03")) {
            } else if (role.getRoleCode().equals("W03")) {
                roleCodes.add(role.getRoleCode());
            }
        }
        if (ShiroUtils.getUser().getAccount().equals("admin")) {
            roleCodes.add("admin");
        }
        model.addAttribute("roleCodes", roleCodes);
        //获取制单人信息
        model.addAttribute("userName", ShiroUtils.getUser().getName());
        //获取出库日期
        model.addAttribute("currentDate", purWarOutManageService.getCurrentDate());
        return "purchase/purWarManage/PurWarOutManage/page";
    }


    @PostMapping("/getWarOutOrderCode")
    @ResponseBody
    /**
     *@FunctionName: getOrderCode
     *@Description: 获取最新的出库单编号
     *@Author: 徐一贺
     *@CreateDate: 2020/3/23 7:55
     *@Phone: 18241927380
     *@Param: [param] 请求参数
     *@Return: com.zhongwang.mms.common.JsonResult
     *@Version: 1.0.0
     */
    public JsonResult getWarOutOrderCode(PurWarOutManageParamModel param) {
        //获取入库单单据编号
        String orderCode = purWarOutManageService.getOrderCode(PurchaseConstant.PCK);
        if (param.getOdrCode() != null && param.getOdrCode().equals(orderCode)) {
            return JsonResult.success("FAIL", orderCode);
        }
        return JsonResult.success("SUCCESS", orderCode);
    }


    @PostMapping("/findDeptList")
    @ResponseBody
    /**
     *@FunctionName: findDeptList
     *@Description: 获取部门列表
     *@Author: 徐一贺
     *@CreateDate: 2020/3/24 13:32
     *@Phone: 18241927380
     *@Param: []
     *@Return: com.zhongwang.mms.common.JsonResult
     *@Version: 1.0.0
     */
    public JsonResult findDeptList() {
        List<TDept> tDeptList = purWarOutManageService.findDeptList();
        return JsonResult.success("", tDeptList);
    }

    @PostMapping("/inventoryList")
    @ResponseBody
    /**
     *@FunctionName: findInventoryList
     *@Description: 外购件出库根据条件查询库存信息
     *@Author: 徐一贺
     *@CreateDate: 2020/3/24 16:49
     *@Phone: 18241927380
     *@Param: [param]
     *@Return: com.zhongwang.mms.common.JsonResult
     *@Version:
     */
    public JsonResult findInventoryList(PInventoryModel param) {
        startPage();
        List<PInventoryModel> inventoryList = purWarOutManageService.findInventoryList(param);
        return jsonResult(inventoryList);
    }


    @PostMapping("/findPInventoryList")
    @ResponseBody
    @RequiresPermissions(value = {"purwar:puroutwar:view", "mecwar:outwar:view", "ykwar:outwar:view"}, logical = Logical.OR)
    /**
     *@FunctionName: findPInventoryList
     *@Description: 获取模态框所需要的的库存信息
     *@Author: 徐一贺
     *@CreateDate: 2020/3/30 10:18
     *@Phone: 18241927380
     *@Param: [param]
     *@Return: com.zhongwang.mms.common.JsonResult
     *@Version:
     */
    public JsonResult findPInventoryList(@RequestParam(value = "existRowStr") String
                                                 existRowStr, PInventoryQueryModel param) {
        List<PInventoryModel> pInventoryModelList = JSON.parseArray(existRowStr, PInventoryModel.class);
        pInventoryModelList.addAll(purWarOutManageService.findInventoryListByIds(param.getItyIds()));
        List<PInventory> regularList = new ArrayList<PInventory>();
        List<PInventory> changeList = new ArrayList<PInventory>();
        List<String> errorList = new ArrayList<>();
        for (PInventoryModel model : pInventoryModelList) {
            PInventory pInventory = purWarOutManageService.getPInventoryByPrimaryKey(model.getItyId());
            if (pInventory.getItyChangeFlag() == null) {
                regularList.add(pInventory);
            } else {
                changeList.add(pInventory);
            }
        }
        if (regularList.size() > 0 && changeList.size() > 0) {
            errorList.add("常规库存不可与串料库存一起出库！<br>");
            errorList.add("以下是串料库存信息！<br>");
            for (PInventory pInventory : changeList) {
                String ityStockTypeStr = "";
                if (pInventory.getItyStockType().equals(1)) {
                    ityStockTypeStr = "【库存在库】";
                    errorList.add("库存类型为：" + ityStockTypeStr + "。物料描述为：【" + pInventory.getItyMatDesc() + "】的库存是【串料库存】。<br>");
                } else {
                    ityStockTypeStr = "【项目在库】";
                    errorList.add("项目编号为：【" + pInventory.getItyProCode() + "】。库存类型为：" + ityStockTypeStr + "。物料描述为：【" + pInventory.getItyMatDesc() + "】的库存是【串料库存】。<br>");
                }

            }
            errorList.add("以下是非串料库存信息！<br>");
            for (PInventory pInventory : regularList) {
                String ityStockTypeStr = "";
                if (pInventory.getItyStockType().equals(1)) {
                    ityStockTypeStr = "【库存在库】";
                    errorList.add("库存类型为：" + ityStockTypeStr + "。物料描述为：【" + pInventory.getItyMatDesc() + "】的库存是【非串料库存】。<br>");
                } else {
                    ityStockTypeStr = "【项目在库】";
                    errorList.add("项目编号为：【" + pInventory.getItyProCode() + "】。库存类型为：" + ityStockTypeStr + "。物料描述为：【" + pInventory.getItyMatDesc() + "】的库存是【非串料库存】。<br>");
                }
                ;
            }
            return JsonResult.fail(errorList.toString());
        }
        return jsonResult(pInventoryModelList);
    }

    @PostMapping("/createRequestMaterial")
    @ResponseBody
    @RequiresPermissions(value = {"purwar:puroutwar:edit", "mecwar:outwar:edit", "ykwar:outwar:edit"}, logical = Logical.OR)
    /**
     *@FunctionName: createRequestMaterial
     *@Description: 创建领料出库单
     *@Author: 徐一贺
     *@CreateDate: 2020/3/23 10:46
     *@Phone: 18241927380
     *@Param: [pOutOrder] 入库数据
     *@Return: com.zhongwang.mms.common.JsonResult 返回结果
     *@Version: 1.0.0
     */
    public JsonResult createRequestMaterial(@RequestBody POutOrder pOutOrder) {
        //验证
        JsonResult jsonResult = new JsonResult();
        List<String> result = new ArrayList<>();
        for (int i = 0; i < pOutOrder.getInsertData().size(); i++) {
            if (pOutOrder.getInsertData().get(i).getOdaNum() == null || pOutOrder.getInsertData().get(i).getOdaNum() == 0) {
                result.add("\n第" + (i + 1) + "行" + " 数量为空 为空<br>");
            } else if (pOutOrder.getInsertData().get(i).getOdaNum() <= 0) {
                result.add("\n第" + (i + 1) + "行" + " 数量必须大于0 数量<br>");
            } else if (pOutOrder.getInsertData().get(i).getOdaNum() > purPInventoryDao.findByPrimaryKey(pOutOrder.getInsertData().get(i).getItyId()).getItyAvaNum()) {
                result.add("\n第" + (i + 1) + "行" + " 数量大于库存可用数量 数量<br>");
            }
        }
        if (result.size() == 0) {
            List<com.zhongwang.mms.module.purchase.model.POrderDetail> recordList = new ArrayList<>();
            for (int i = 0; i < pOutOrder.getInsertData().size(); i++) {
                boolean exist = false;
                for (int j = 0; j < recordList.size(); j++) {
                    if (recordList.get(j).getItyId().equals(pOutOrder.getInsertData().get(i).getItyId())) {
                        exist = true;
                        recordList.get(j).setOdaNum(recordList.get(j).getOdaNum() + pOutOrder.getInsertData().get(i).getOdaNum());
                        if (recordList.get(j).getOdaNum() > purPInventoryDao.findByPrimaryKey(recordList.get(j).getItyId()).getItyAvaNum()) {
                            List<Integer> errorList = recordList.get(j).getErrorLineNumlist();
                            errorList.add(i + 1);
                            recordList.get(j).setErrorLineNumlist(errorList);
                        }
                    }
                }
                if (exist == false) {
                    com.zhongwang.mms.module.purchase.model.POrderDetail obj = pOutOrder.getInsertData().get(i);
                    obj.getErrorLineNumlist().add(i + 1);
                    recordList.add(obj);
                }
            }
            for (int i = 0; i < recordList.size(); i++) {
                Double avaNum = purPInventoryDao.findByPrimaryKey(recordList.get(i).getItyId()).getItyAvaNum();
                if (recordList.get(i).getErrorLineNumlist().size() > 1) {
                    result.add("\n第" + (recordList.get(i).getErrorLineNumlist().toString()) + "行" + " 是一个库存其出库数之和大于库存可用量，无法出库,当前物料库存可用数量为【" + new BigDecimal(avaNum) + "】 数量<br>");
                }
            }
        }
        if (result.size() > 0) {
            result.add("\n单据保存失败，请先维护以上出库信息！");
            jsonResult.setData(result);
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("单据保存失败,请检查出库库存的数量是否充足！");
            return jsonResult;
        }
        AllocationResaultModel allocationResaultModel = new AllocationResaultModel();
        allocationResaultModel.setIsChangeFlag(0);
        try {
            String code = purWarOutManageService.getOrderCode(PurchaseConstant.PCK);
            allocationResaultModel = purWarOutManageService.createRequestMaterial(pOutOrder,code,allocationResaultModel);
            if(allocationResaultModel.getMessage().equals("单据保存成功！")){
                //其中过程中所有库存信息中的数量不可被调整
                allocationResaultModel.setInsertData(pOutOrder.getInsertData());
                allocationResaultModel.setOdrCode(code);
                result.add(allocationResaultModel.getMessage());
                jsonResult.setData(result);
                jsonResult.setType(JsonResult.ResultType.SUCCESS);
                jsonResult.setData(allocationResaultModel);
                //记录操作日志
                logService.saveLog("出入库操作-领料出库", "出库单据编码：" + code);
            }else{
                result.add(allocationResaultModel.getMessage());
                jsonResult.setData(result);
                jsonResult.setType(JsonResult.ResultType.ERROR);
                jsonResult.setData(allocationResaultModel);
            }

        }catch (Exception e){
            log.error("领料出库异常："+e.getMessage());
            //记录异常错误日志信息
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("单据保存失败,请检查出库库存的数量是否充足！");
        }
        return jsonResult;
    }
}